package org.zebra.common.crypto;

import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhanghongbin
 */
public class Sm2CryptoProvider implements CryptoProvider {

    private String publicKey;

    public Sm2CryptoProvider(String publicKey, String privateKey) {
        this.publicKey = publicKey;
        this.privateKey = privateKey;
    }

    private String privateKey;

    @Override
    public String encrypt(String value) {
        SM2 sm2 = SmUtil.sm2(null, publicKey);
        return sm2.encryptBase64(value, StandardCharsets.UTF_8, KeyType.PublicKey);
    }

    @Override
    public String decrypt(String value) {
        SM2 sm2 = SmUtil.sm2(privateKey, null);
        return sm2.decryptStr(value, KeyType.PrivateKey, StandardCharsets.UTF_8);
    }

    public static Map<String, String> generateKey() {
        Map<String, String> keyMap = new HashMap<>(2);
        SM2 sm2 = SmUtil.sm2();
        keyMap.put("privateKey", sm2.getPrivateKeyBase64());
        keyMap.put("publicKey", sm2.getPublicKeyBase64());
        return keyMap;
    }
}
